<template>
  <section class="login-wrap">
    <Form ref='form' class="login-form">
      <h3>国家电网公司</h3>
      <div class="fields">
        <Form-item prop="account" style="margin-bottom: 0">
          <Row :gutter="8">
            <Col span="20">
              <Input
                long
                v-model="login.account"
                placeholder="账号"
              >
              </Input>
            </Col>
            <Col span="4">
              <Button
                  long
                  @click.native="handleRegister"
                  type="success"
                  :loading="loading"
                  icon="android-person-add"
                >
              </Button>
            </Col>
          </Row>
        </Form-item>

        <Form-item prop="password" style="margin-bottom: 0">
          <Input
            class="field"
            v-model="login.password"
            type="password"
            placeholder="密码"
            width="370px"
            @keyup.enter.native="check"
          >
          </Input>
        </Form-item>

        <Form-item prop="projectname" style="margin-bottom: 0">
          <Row :gutter="8">
              <Col span="12">
                <Select v-model="login.projectname">
                    <Option v-for="(item,index) in login.projects" :key="index" :value="item.projectname">{{item.projectname}}</Option>
                  </Select>
              </Col>
              <Col span="4">
                <Button
                  long
                  @click.native="refreshMyProjects"
                  type="success"
                  :loading="loading"
                  icon="ios-loop-strong"
                >
                </Button>
              </Col>
              <Col span="4">
                <Button
                  long
                  @click.native="handleAddProjectModal"
                  type="success"
                  :loading="loading"
                  icon="plus-round"
                >
                </Button>
              </Col>
              <Col span="4">
                <Button
                  long
                  @click.native="handleDeleteProject"
                  type="success"
                  :loading="loading"
                  icon="minus"
                >
                </Button>
              </Col>
          </Row>
        </Form-item>

      </div>
      <div class="submit">
        <Button
          long
          @click.native="check"
          type="primary"
          :loading="loading"
        >
          {{ loading ? '登录中' : '登录' }}
        </Button>
      </div>
    </Form>

    <Modal
      long
      width="300"
      title="添加项目"
      v-model="addprojectmodal"
      style="top:300px;"
      @on-ok="handleAddProject"
      >
      <p><Input v-model="newprojectname" placeholder="Enter your project name"></Input></p>
      <p style="margin-top:10px;"><Alert type="success" show-icon>ms-xxx | ma-xxx | ms-base-xxx</Alert></p>
      <p><Alert type="error" show-icon>xxx-server | aa-xxx</Alert></p>
    </Modal>

    <Modal
      long
      width="450"
      title="初始化配置"
      v-model="initmodal"
      :loading="initloading"
      :closable="false"
      :mask-closable="false"
      @on-ok="handleSaveConfig">
      <p>
        <Form ref="form" :model="form" :label-width="100" label-position="right" :rules="formValidate">
          <FormItem label="服务端IP：" prop="serverip">
            <Input v-model="form.serverip"></Input>
          </FormItem>
          <FormItem label="服务端端口：" prop="serverport">
            <Input v-model="form.serverport"></Input>
          </FormItem>
        </Form>
      </p>
    </Modal>

    <canvas id="J_loginBackground"></canvas>
  </section>
</template>

<script>
  const session = require('electron').remote
  import { render } from '../config/canvas'
  const {dialog} = require('electron').remote
  const {ipcRenderer} = require('electron')
  export default {
    data () {
      return {
        login: {
          account: '',
          password: '',
          projectname: '',
          projects: []
        },
        form: {
          serverip: localStorage.getItem('serverip'),
          serverport: localStorage.getItem('serverport')
        },
        formValidate: {
          serverip: [
            { required: true, message: '请输入服务端IP', trigger: 'blur' }
          ],
          serverport: [
            { required: true, message: '请输入服务端端口', trigger: 'blur' }
          ]
        },
        remember: [],
        loading: false,
        initloading: true,
        addprojectmodal: false,
        initmodal: false,
        newprojectname: '',
        bgcanvas: {}
      }
    },
    methods: {
      render: render,
      check () {
        if (this.login.account === '') {
          return this.$Notice.error({
            title: '用户名不能为空',
            duration: 2
          })
        }
        if (this.login.password === '') {
          return this.$Notice.error({
            title: '密码不能为空',
            duration: 2
          })
        } else if (this.login.password.length < 3) {
          return this.$Notice.error({
            title: '密码不能少于3个字符',
            duration: 2
          })
        } else {
          this.loading = true
          let self = this
          this.$axios.get(self.$util.server+'user/login?username=' + self.login.account + '&password=' + self.login.password + '&projectname=' + self.login.projectname, {}, {
            headers: {
              'Content-Type': 'application/json;charset=utf-8'
            }
          }).then(function (response) {
            self.loading = false
            // 这里是处理正确的回调
            if (response.data.ok) {
              self.loading = false;
              console.info(response.data.data)

              localStorage.setItem('authorization', response.data.data.token?response.data.data.token:'')//用户名
              localStorage.setItem('user', response.data.data.user.username?response.data.data.user.username:'')//用户名
              localStorage.setItem('userid', response.data.data.user.userid?response.data.data.user.userid:'')//用户ID
              localStorage.setItem('projectname', response.data.data.config.projectname?response.data.data.config.projectname:'')//项目名 例如ma-test
              localStorage.setItem('name', response.data.data.config.projectname?self.getPackageName(response.data.data.config.projectname):'')//包名 例如test
              localStorage.setItem('developerconfigurationid', response.data.data.config.developerconfigurationid?response.data.data.config.developerconfigurationid:'')
              localStorage.setItem('clientcodelist', response.data.data.config.clientcodelist?response.data.data.config.clientcodelist:'')
              localStorage.setItem('mysqldatabase', response.data.data.config.mysqldatabase?response.data.data.config.mysqldatabase:'')
              localStorage.setItem('mysqlhost', response.data.data.config.mysqlhost?response.data.data.config.mysqlhost:'')
              localStorage.setItem('mysqlpassword', response.data.data.config.mysqlpassword?response.data.data.config.mysqlpassword:'')
              localStorage.setItem('mysqlport', response.data.data.config.mysqlport?response.data.data.config.mysqlport:'')
              localStorage.setItem('mysqluser', response.data.data.config.mysqluser?response.data.data.config.mysqluser:'')
              localStorage.setItem('servercodelist', response.data.data.config.servercodelist?response.data.data.config.servercodelist:'')
              localStorage.setItem('account', self.login.account?self.login.account:'')
              localStorage.setItem('password', self.login.password?self.login.password:'')

              //获取系统用户列表
              self.$axios.get(self.$util.server+'user/list', {}, {
                headers: {
                  "Content-Type":"application/json;charset=utf-8"
                },
              }).then(function(response) {
                console.log(response)
                if(response.data && response.data.length>0) {
                  localStorage.setItem('alluser', JSON.stringify(response.data));
                }
              }).catch( function(response) {
                console.log(response)
                self.$Message.warning({content: '请求超时! </br> 服务IP：'+localStorage.getItem('serverip')+'，端口：'+localStorage.getItem('serverport') + '</br> 可使用快捷键 <font color="red">ctrl+i</font> 修改配置！',duration: 10})
              });

              self.$Message.success({content: '登录成功',duration: 2})
              self.$router.push({name: 'ownspace_index'})
            } else {
              return self.$Notice.error({
                title: '用户名、密码或项目名错误！',
                duration: 2
              })
            }
          }).catch(function (response) {
            self.loading = false
            self.$Message.warning({content: '请求超时! </br> 服务IP：'+localStorage.getItem('serverip')+'，端口：'+localStorage.getItem('serverport') + '</br> 可使用快捷键 <font color="red">ctrl+i</font> 修改配置！',duration: 10})
            console.log(response)
          })
        }
      },
      refreshMyProjects(){
        var self = this;
        let account = self.login.account;
        let password = self.login.password;
        if(account && password){
          self.$axios.get(self.$util.server+'user/getprojects?username='+account+'&password='+password, {}, {
            headers: {
                "Content-Type":"application/json;charset=utf-8"
            },
          }).then(function(response) {
            console.log(response)
            if(response.data && response.data.code==200) {
              self.login.projects = response.data.data;
              self.login.projectname = '';
              localStorage.setItem('projects', JSON.stringify(response.data.data));
            }else{
              self.$Message.warning({content: '用户名或密码错误!',duration: 2})
            }
          }).catch( function(response) {
            console.log(response)
            self.$Message.warning({content: '请求超时! </br> 服务IP：'+localStorage.getItem('serverip')+'，端口：'+localStorage.getItem('serverport') + '</br> 可使用快捷键 <font color="red">ctrl+i</font> 修改配置！',duration: 10})
          });
        }else{
          self.$Message.warning({content: '用户名或密码不能为空!',duration: 2})
        }
      },
      handleRegister () {
        var self = this;
        let account = self.login.account;
        let password = self.login.password;
        if(account && password){
          self.$axios.get(self.$util.server+'user/register?username='+account+'&password='+password, {}, {
            headers: {
                "Content-Type":"application/json;charset=utf-8"
            },
          }).then(function(response) {
            console.log(response)
            if(response.data && response.data.code==200) {
              self.$Message.success({content: '注册成功！',duration: 2})
              self.login.projectname = '';
            }else{
              self.$Message.warning({content: response.data.msg,duration: 2})
            }
          }).catch( function(response) {
            console.log(response)
            self.$Message.warning({content: '请求超时! </br> 服务IP：'+localStorage.getItem('serverip')+'，端口：'+localStorage.getItem('serverport') + '</br> 可使用快捷键 <font color="red">ctrl+i</font> 修改配置！',duration: 10})
          });
        }else{
          self.$Message.warning({content: '用户名或密码不能为空!',duration: 2})
        }
      },
      handleAddProjectModal () {
        this.addprojectmodal = true;
      },
      handleAddProject() {
        let self = this;
        let newprojectname = this.newprojectname;

        if(newprojectname){

          let _packageName = "null";
          if(newprojectname.indexOf("ms-base-")!=-1) {
            _packageName = newprojectname.replace("ms-base-", "");
          }
          if(newprojectname.indexOf("ma-base-")!=-1) {
            _packageName = newprojectname.replace("ma-base-", "");
          }
          if(newprojectname.indexOf("ms-")!=-1) {
            _packageName = newprojectname.replace("ms-", "");
          }
          if(newprojectname.indexOf("ma-")!=-1) {
            _packageName = newprojectname.replace("ma-", "");
          }
          //判断newprojectname是否合法
          if(_packageName=="null" || _packageName.indexOf("-")!=-1){
            self.$Message.warning({content: '新项目名不合法',duration: 2})
          }else{
            let account = this.login.account;
            let password = this.login.password;
            if(newprojectname && account && password){
              self.$axios.get(self.$util.server+'user/addproject?username='+account+'&password='+password+'&projectname='+newprojectname, {}, {
                headers: {
                    "Content-Type":"application/json;charset=utf-8"
                },
              }).then(function(response) {
                console.log(response)
                if(response.data && response.data.code==200) {
                  self.$Message.success({content: '添加成功！',duration: 2})
                  self.login.projects.push({"projectname":newprojectname});
                  self.login.projectname = newprojectname;
                  localStorage.setItem('projects', JSON.stringify(self.login.projects));
                }else{
                  self.$Message.warning({content: response.data.msg,duration: 2})
                }
              }).catch( function(response) {
                console.log(response)
                self.$Message.warning({content: '请求超时! </br> 服务IP：'+localStorage.getItem('serverip')+'，端口：'+localStorage.getItem('serverport') + '</br> 可使用快捷键 <font color="red">ctrl+i</font> 修改配置！',duration: 10})
              });
            }else{
              self.$Message.warning({content: '新项目名、用户名或密码不能为空',duration: 2})
            }
          }
        }else{
          self.$Message.warning({content: '新项目名不能为空',duration: 2})
        }

      },
      handleDeleteProject(){
        let self = this;
        let projectname = this.login.projectname;
        let account = this.login.account;
        let password = this.login.password;
        if(projectname && account && password){
          self.$Modal.confirm({
              title: '删除项目',
              content: '<p>数据删除后不可恢复，确认删除项目吗？</p>',
              onOk: () => {
                self.$axios.get(self.$util.server+'user/delproject?username='+account+'&password='+password+'&projectname='+projectname, {}, {
                  headers: {
                      "Content-Type":"application/json;charset=utf-8"
                  },
                }).then(function(response) {
                  console.log(response)
                  if(response.data && response.data.code==200) {
                    self.handleDeleteLocalProject(projectname);
                  }else{
                    self.$Message.warning({content: response.data.msg,duration: 2})
                  }
                }).catch( function(response) {
                  console.log(response)
                  self.$Message.warning({content: '请求超时! </br> 服务IP：'+localStorage.getItem('serverip')+'，端口：'+localStorage.getItem('serverport') + '</br> 可使用快捷键 <font color="red">ctrl+i</font> 修改配置！',duration: 10})
                });
              },
              onCancel: () => {}
          });
        }else{
          self.$Message.warning({content: '项目、用户名或密码不能为空',duration: 2})
        }
      },
      handleDeleteLocalProject(pname){
        var projects_str = localStorage.getItem('projects');
        var projects=[],new_projects = [];
        if(projects_str) projects = JSON.parse(projects_str);
        if(projects && projects.length>0){
          for(let i=0;i<projects.length;i++){
            if(projects[i].projectname != pname){
              new_projects.push(projects[i]);
            }
          }
          localStorage.setItem('projects',JSON.stringify(new_projects));
          this.login.projects = new_projects;
          this.login.projectname = '';
        }
      },
      handleSaveConfig(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            //保存缓存
            localStorage.setItem('serverip', this.form.serverip)
            localStorage.setItem('serverport', this.form.serverport)
            //更新全局变量
            this.$util.server = 'http://' + this.form.serverip + ':' + this.form.serverport + '/';///standard

            this.initmodal = false;
            this.$Message.success({content: '保存成功！ip:'+this.form.serverip+',端口:'+this.form.serverport,duration: 5})
          }else{
            setTimeout(() => {
              this.initloading = false;
            }, 100);
            setTimeout(() => {
              this.initloading = true;
            }, 200);
          }
        });
      },
      //从项目名称获取包名称
      getPackageName(serverName){
        let _packageName = "null";
        if(serverName.indexOf("ms-base-")!=-1) {
          _packageName = serverName.replace("ms-base-", "");
        }
        if(serverName.indexOf("ma-base-")!=-1) {
          _packageName = serverName.replace("ma-base-", "");
        }
        if(serverName.indexOf("ms-")!=-1) {
          _packageName = serverName.replace("ms-", "");
        }
        if(serverName.indexOf("ma-")!=-1) {
          _packageName = serverName.replace("ma-", "");
        }
        //判断serverName是否合法
        if(_packageName=="null" || _packageName.indexOf("-")!=-1){
          return "null";
        }
        //若serverName是xxx-xxx-xxx-xxx 总返回最后一个xxx
        var arr = serverName.split("-");
        if(arr.length>2) {
          return arr[arr.length-1];
        }
        return _packageName;
      }
    },
    watch: {
      '$route' () {
        if (this.$route.name === 'login') {
          console.log(111111111)
          this.render()
        }
      }
    },
    created () {
      let account = localStorage.getItem('account')
      let password = localStorage.getItem('password')
      let projectname = localStorage.getItem('projectname')
      if(account && password && projectname){
        this.login.account = account
        this.login.password = password
        this.login.projectname = projectname
      }
    },
    mounted () {

      //如果没有服务端相关的默认配置 则弹出配置框
      if(!localStorage.getItem('serverip') || !localStorage.getItem('serverport')){
        this.initmodal = true;
      }

      // 清除全部消息监听
      ipcRenderer.removeAllListeners('tips')

      ipcRenderer.send('version','')

      console.log(localStorage.getItem('projects'))
      this.login.projects = JSON.parse(localStorage.getItem('projects'));

      // 接收消息
      ipcRenderer.on('tips', (event, content) => {
          console.log('content：'+content)
          if(content == 'openInitDialog'){
            this.initmodal = !this.initmodal;
          }else{
            let json_content = JSON.parse(content);
            localStorage.setItem('currentVersion', json_content.version);
            console.log('json_content.version：'+json_content.version)
          }
      })
      console.log(2222222)
      var a = this.render()
      console.log(a)
    }
  }
</script>

<style lang="less" scoped>
  .login-wrap {
    position: fixed;
    z-index: 0;
    top: 0;
    left: 0;
    overflow: hidden;
    width: 100%;
    height: 100%;
    background: #111;
    canvas {
      width: 100%;
      height: 100%;
      position: absolute;
    }
  }
  .login-form {
    position: absolute;
    z-index: 1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    padding: 16px 20px 0;
    width: 410px;
    height: 282px;
    font-size: 14px;
    background: #fff;
    border: 1px solid #ccc;
    border-radius: 12px;
    box-shadow: 2px 2px 32px 1px rgba(0, 0, 0, .45);
    opacity: .75;
    h3 {
      margin-top: 0;
      margin-bottom: 0;
      padding: 12px 0;
      font-weight: normal;
      font-size: 22px;
      text-align: center;
    }
    .field {
      display: block;
      margin: 0 auto;
      padding: 6px 0;
    }
    .submit {
      padding: 12px 0;
    }
  }
</style>
